package cn.wolfcode.shop.cloud.filter;

import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.feign.MemberFeignApi;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieRefreshFilter extends ZuulFilter {

    @Autowired
    private MemberFeignApi memberFeignApi;

    //1、声明过滤器的类型
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }
    //2、设置过滤器优先级，数值越低，优先级越高
    @Override
    public int filterOrder() {
        return 0;
    }
    //3、在该方法中判断用户是否携带了token，若携带了token，则返回为true，可执行run方法
    @Override
    public boolean shouldFilter() {
        //获取resquest对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //获取cookie
        String token = CookieUtil.getToken("userToken",request);
        //判断用户是否携带了token
        if(token!=null){
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //获取resquest对象
        //获取cookie
        String token = CookieUtil.getToken("userToken",request);
        //调用远程服务，延长redis的过期时间
        Result<Boolean> result = memberFeignApi.refreshRedis(token);
        if(result!=null && result.getCode()==200 && result.getData()){
            //延长cookie的有效时间
            HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
            CookieUtil.addCookie("userToken",token ,1800 , response);
        }
        //若有多个filter，设置成false就不会执行后面的filter了
        currentContext.setSendZuulResponse(false);
        return null;
    }
}
